<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>流程处理</title>
    <link rel="stylesheet" href="../../../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../../admin/css/reset.css"/>
    <!--LogicFlow core包css-->
    <link rel="stylesheet" href="../../../../logicflow/core/dist/style/index.css"/>
    <!--LogicFlow extension包css-->
    <link rel="stylesheet" href="../../../../logicflow/extension/lib/style/index.css"/>
    <style>
        html, body {
            overflow: hidden;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        .lf-control-see {
            background-image: url('');
        }

        .lf-control-import {
            background-image: url('');
        }

        .lf-control-clear {
            background-image: url('');
        }

        .lf-control-save {
            background-image: url('');
        }

        .lf-control-refresh {
            background-image: url("");
        }

        .lf-control-exit {
            background-image: url('');
        }


        .custom-minimap {
            background-image: url();
        }

        #lf-graph {
            margin: 20px 20px 0px 20px;
            width: 98%;
            height: 100%;
        }


        /*tab title*/
        .drawer-section-list ul li {
            display: inline-block;
            zoom: 1;
            vertical-align: top;
            margin-right: 20px;
            font-size: 16px;
            line-height: 34px;
            color: #373d40;
            cursor: pointer;
        }

        /*选中下划线*/
        .drawer-section-list ul .on {
            color: #488bff;
            border-bottom: 1px solid #488bff;
        }

        /*列表*/
        .drawer-section-info div {
            text-align: left;
            border-top: 1px solid #ececec;
        }

        .task-form-label {
            text-align: left;
            width: 120px;
        }

        .task-form-text {
            display: block;
            padding: 9px 15px;
        }
    </style>
</head>

<body>
<div>
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-tab layui-tab-brief">
                <ul class="layui-tab-title">
                    <li class="layui-this">表单信息</li>
                    <li>任务处理</li>
                    <li>流程图</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <!--表单信息-->
                        <form class="layui-form" id="form-container" lay-filter="forms"></form>
                    </div>
                    <div class="layui-tab-item">
                        <!--任务处理-->
                        <form class="layui-form" action="">
                            <!--任务信息-->
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <label class="layui-form-label task-form-label">任务信息</label>
                                </div>
                                <div class="layui-card-body">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label task-form-label">任务名称:</label>
                                        <div class="layui-input-block">
                                            <span class="task-form-text" id="display-name"></span>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label task-form-label">流程发起人:</label>
                                        <div class="layui-input-block">
                                            <span class="task-form-text" id="operator"></span>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label task-form-label">任务开始时间:</label>
                                        <div class="layui-input-block">
                                            <span class="task-form-text" id="create-time"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!--意见信息-->
                            <br/>
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <label class="layui-form-label task-form-label">意见信息</label>
                                </div>
                                <div class="layui-card-body">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label task-form-label">处理意见:</label>
                                        <div class="layui-input-inline">
                                            <select name="handling" lay-filter="handling">
                                                <option value=""></option>
                                                <option value="1">同意</option>
                                                <option value="2">同意***的意见</option>
                                                <option value="3">请指示</option>
                                                <option value="4">请***阅示</option>
                                                <option value="5">请处理</option>
                                                <option value="6">不同意</option>
                                                <option value="7">呈领导阅示</option>
                                                <option value="8">请审批</option>
                                                <option value="9">审核无误</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <div class="layui-input-inline" style="width: 100%">
                                            <textarea placeholder="请输入处理意见" name="approval_opinion" class="layui-textarea"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="layui-tab-item">
                        <div class="layui-form-item" style="width: 100%;height: 500px;">
                            <!--流程图-->
                            <div id="lf-graph"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div style="position: absolute;left: 15px;">
            <button class="pear-btn pear-btn-md layui-bg-orange">
                驳回
                <span>|</span>
                <i class="layui-icon layui-icon-down layui-font-12 demo-dropdown-align" lay-options="{}" id="demo-dropdown-align"></i>
            </button>
        </div>
        <div class="button-container">
            <button type="button" class="pear-btn pear-btn-primary pear-btn-md" lay-on="agree" data-value="1">同意</button>
            <button type="button" class="pear-btn pear-btn-primary pear-btn-md" lay-on="disagree" data-value="0">不同意</button>
            <button type="button" class="pear-btn pear-btn-md" lay-on="close">取消</button>
        </div>
    </div>
</div>


<script src="../../../../component/layui/layui.js"></script>
<script src="../../../../component/pear/pear.js"></script>
<script src="../../../../lms/base64.js"></script>
<script src="../../../../lms/common.js"></script>
<script src="../../../../lms/permission.js"></script>
<script src="../../../../lms/config.js"></script>

<script type="text/javascript" src="../../../../logicflow/core/dist/logic-flow.js"></script>
<!--LogicFlow的插件引入-->
<script type="text/javascript" src="../../../../logicflow/extension/lib/Menu.js"></script>
<script type="text/javascript" src="../../../../logicflow/extension/lib/DndPanel.js"></script>
<script type="text/javascript" src="../../../../logicflow/extension/lib/Control.js"></script>
<script type="text/javascript" src="../../../../logicflow/extension/lib/MiniMap.js"></script>
<script type="text/javascript" src="../../../../logicflow/extension/lib/Group.js"></script>
<!--LogicFlow定制模型引入-->
<script type="text/javascript" src="../../../../logicflow/customized/start.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/task.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/fork.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/join.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/subProcess.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/wfSubProcess.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/end.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/custom.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/decision.js"></script>
<script type="text/javascript" src="../../../../logicflow/customized/transition.js"></script>


<script>

    const PRIMARY_KEY = "id";
    const EXECUTE_API = lms_config.api_url + "/adminapi/wf/task/execute";
    const BACKOFF_API = lms_config.api_url + "/adminapi/wf/task/backoff"
    const DETAIL_API = lms_config.api_url + "/adminapi/wf/task/get";
    const HIGH_LIGHT_API = lms_config.api_url + "/adminapi/wf/order/highLightData";

    // 字段设置
    layui.use(["common", "popup", "form", "jquery", "dropdown", "util"], function () {
        let popup = layui.popup;
        let form = layui.form;
        let util = layui.util;
        let $ = layui.jquery;
        let dropdown = layui.dropdown;
        let htmlFilePath = '../../../../view/wf/template/'
        let logicfolw;

        /**
         * 静默模式参数
         * @type {{stopZoomGraph: boolean, nodeSelectedOutline: boolean, nodeTextDraggable: boolean, edgeTextDraggable: boolean, stopScrollGraph: boolean, hideAnchors: boolean, adjustEdgeStartAndEnd: boolean, nodeTextEdit: boolean, adjustEdge: boolean, adjustNodePosition: boolean, edgeTextEdit: boolean, stopMoveGraph: boolean}}
         */
        const SilentConfig = {
            stopZoomGraph: false,
            stopScrollGraph: false,
            stopMoveGraph: false,
            adjustEdge: false,
            adjustEdgeStartAndEnd: false,
            adjustNodePosition: false,
            hideAnchors: true,
            nodeSelectedOutline: true,
            nodeTextEdit: false,
            edgeTextEdit: false,
            nodeTextDraggable: false,
            edgeTextDraggable: false,
        }

        /**
         * 流程图渲染
         * @param data
         */
        const lf = new LogicFlow({
            container: document.querySelector("#lf-graph"),
            grid: {
                size: 20,
                visible: true,
                type: 'dot',
                config: {
                    color: '#ababab',
                    thickness: 1,
                },
            },
            plugins: [Menu, DndPanel, Control, MiniMap, GroupNode],
            keyboard: {
                enabled: true,//是否启用快捷键
                shortcuts: [
                    {
                        keys: ["del"],
                        callback: () => {
                            if (!lf) return;
                            const elements = lf.getSelectElements(true);
                            lf.clearSelectElements();
                            elements.edges.forEach((edge) => lf.deleteEdge(edge.id));
                            elements.nodes.forEach((node) => lf.deleteNode(node.id));
                        }
                    }
                ]
            },
        });

        //图像注册
        lf.register(Task);
        lf.register(Fork);
        lf.register(Start);
        lf.register(Decision);
        lf.register(End);
        lf.register(Join);
        lf.register(Custom);
        lf.register(SubProcess);
        lf.register(WfSubProcess);
        lf.register(Transition);


        util.on('lay-on', {
            close: function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            },
            agree: function () {
                let task_id = getQueryString(PRIMARY_KEY);
                if (!task_id) {
                    return false;
                }
                let approval_type = $('[lay-on="agree"]').data('value');
                let approval_opinion = $('textarea[name="approval_opinion"]').val();
                if (!approval_opinion) {
                    popup.failure('请填写不同意描述');
                    return false;
                }
                let data = {
                    task_id: task_id,
                    args: {
                        approval_type: approval_type,
                        approval_opinion: approval_opinion
                    }
                };
                execute(data)
            },
            disagree: function () {
                let task_id = getQueryString(PRIMARY_KEY);
                if (!task_id) {
                    return false;
                }
                let approval_type = $('[lay-on="disagree"]').data('value');
                let approval_opinion = $('textarea[name="approval_opinion"]').val();
                if (!approval_opinion) {
                    popup.failure('请填写不同意描述');
                    return false;
                }
                let data = {
                    task_id: task_id,
                    args: {
                        approval_type: approval_type,
                        approval_opinion: approval_opinion
                    }
                };
                execute(data)
            }
        });

        /**
         * 任务驳回
         * @param data
         */
        function backOff(data) {
            layui.$.ajax({
                url: BACKOFF_API,
                type: 'POST',
                dateType: "json",
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (ret) {
                    if (ret.status == 200) {
                        popup.success(ret.msg, function () {
                            parent.refreshTable();
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                        });
                    } else {
                        popup.failure(ret.msg);
                    }
                }
            });

        }

        /**
         * 任务执行
         * @param data
         */
        function execute(data) {
            layui.$.ajax({
                url: EXECUTE_API,
                type: 'POST',
                dateType: "json",
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (ret) {
                    if (ret.status == 200) {
                        popup.success(ret.msg, function () {
                            parent.refreshTable();
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                        });
                    } else {
                        popup.failure(ret.msg);
                    }
                }
            });

        }


        /**
         * 任务详情获取
         */
        function get() {
            layui.$.ajax({
                url: DETAIL_API,
                type: 'POST',
                dateType: "json",
                async: false,
                contentType: 'application/json',
                data: JSON.stringify({id: getQueryString(PRIMARY_KEY)}),
                success: function (ret) {
                    if (ret.status == 200) {
                        let process = ret.data['processs'] ?? [];
                        let instanceUrl = process['instance_url'] ?? '';
                        logicfolw = process['content'] != undefined ? process['content'] : {};
                        formRendering(htmlFilePath + instanceUrl);//表单渲染
                        highLightData(ret.data['order_id']);//高亮数据

                        //表单渲染
                        let orders = ret.data['orders'] != undefined ? ret.data['orders'] : {};
                        let forms = orders['variable'] != undefined ? orders['variable'] : {};
                        form.val('forms', forms)

                        //任务信息
                        $('#display-name').html(ret.data['display_name'] != undefined ? ret.data['display_name'] : '');
                        $('#operator').html(forms['operator_real_name'] != undefined ? forms['operator_real_name'] : '');
                        $('#create-time').html(ret.data['create_time'] != undefined ? ret.data['create_time'] : '');

                        window.onload = function () {
                            // 获取表单元素
                            let container = document.getElementById("form-container");
                            // 遍历表单元素设置为只读
                            for (let i = 0; i < container.elements.length; i++) {
                                let element = container.elements[i];
                                element.disabled = true;
                            }
                        };

                        form.render();
                        lf.render(logicfolw);

                    }
                }
            });
        }

        /**
         * 赋值审批意见
         */
        form.on('select(handling)', function (obj) {
            let selectedText = obj.elem.options[obj.elem.selectedIndex].text;
            $('textarea[name="approval_opinion"]').val(selectedText);
        });


        /**
         * 表单渲染
         * @param htmlFilePath
         * @returns {boolean}
         */
        function formRendering(htmlFilePath) {
            if (htmlFilePath === '') {
                $('#form-container').html('')
                return false
            }
            $.ajax({
                url: htmlFilePath + '.html', // test.html文件的路径
                type: 'GET',
                dataType: 'html',
                async: false,
                success: function (response) {
                    $('#form-container').html(response);
                    form.render()
                }
            });
        }

        /**
         * 流程高亮
         * @param orderId
         * @returns {boolean}
         */
        function highLightData(orderId) {
            if (orderId === '') {
                return false;
            }
            layui.$.ajax({
                url: HIGH_LIGHT_API,
                type: 'POST',
                dateType: "json",
                contentType: 'application/json',
                data: JSON.stringify({id: orderId}),
                success: function (ret) {
                    if (ret.status == 200) {
                        let data = ret.data['history_node_names'] !== undefined ? ret.data['history_node_names'] : [];
                        let downList = [];
                        $.each(data, function (index, value) {
                            $.each(logicfolw['nodes'], function (index, item) {
                                if (value === item.id && item.type === 'workingflower:task') {
                                    downList.push({
                                        id: item.id,
                                        title: item.text.value
                                    });
                                }
                            })
                        })
                        //渲染回退按钮
                        dropdown.render({
                            elem: '#demo-dropdown-align',
                            data: downList,
                            click: function (data) {
                                //执行回退逻辑
                                let task_id = getQueryString(PRIMARY_KEY);
                                let param = {
                                    task_id: task_id,
                                    args: {
                                        target_node_name: data.id,
                                        approval_opinion: '退回【' + data.title + '】节点'
                                    }
                                }
                                backOff(param)
                            }
                        });
                        //流程图高亮
                        let list = ret.data !== undefined ? ret.data : [];
                        setHighLight(list)
                    }
                }
            });
        }

        /**
         * 高亮设置
         * @param data
         */
        function setHighLight(data) {

            if (!lf || !data) {
                return;
            }
            // 设置历史节点
            if (data && data['history_node_names'] !== undefined) {
                data['history_node_names'].forEach(nodeName => {
                    let nodeModel = lf.getNodeModelById(nodeName)
                    nodeModel.setProperties({state: 'history'})
                })
            }
            // 设置历史边
            if (data && data['history_edge_names']) {
                data['history_edge_names'].forEach(edgeName => {
                    let edgeModel = lf.getEdgeModelById(edgeName)
                    if (edgeModel) {
                        edgeModel.setProperties({state: 'history'})
                    }
                })
            }
            // 设置当前节点
            if (data && data['active_node_names']) {
                data['active_node_names'].forEach(nodeName => {
                    lf.setProperties(nodeName, {state: 'active'})
                })
            }
        }

        get();
    });

</script>

</body>
</html>
